const app = getApp()
const request = require('../../utils/request')

Page({
  data: {
    addressId: null,
    isEdit: false,
    isLoading: false,
    formData: {
      name: '',
      phone: '',
      province: '',
      city: '',
      district: '',
      detailAddress: '',
      isDefault: false,
      tag: ''
    },
    tags: ['家', '公司', '学校', '其他'],
    selectedTag: '',
    region: ['请选择省市区'],
    showRegionPicker: false,
    loading: false,
    saving: false
  },

  onLoad(options) {
    if (options.id) {
      this.setData({
        addressId: options.id,
        isEdit: true,
        loading: true
      })
      wx.setNavigationBarTitle({
        title: '编辑地址'
      })
      this.fetchAddressDetail(options.id)
    } else {
      wx.setNavigationBarTitle({
        title: '添加地址'
      })
    }
  },

  fetchAddressDetail(addressId) {
    request.get(`/address/${addressId}`, {}, {
      mock: {
        id: addressId,
        userId: app.getSafeUserId(),
        name: '张三',
        phone: '13812345678',
        province: '北京市',
        city: '北京市',
        district: '朝阳区',
        detailAddress: '光华路甲8号院中海广场C1座2102室',
        isDefault: true,
        tag: '家',
        createdAt: '2023-08-01T12:00:00'
      }
    }).then(res => {
      this.setData({ loading: false })
      
      if (res.code === 200 && res.data) {
        const address = res.data
        
        this.setData({
          formData: {
            name: address.name || '',
            phone: address.phone || '',
            province: address.province || '',
            city: address.city || '',
            district: address.district || '',
            detailAddress: address.detailAddress || '',
            isDefault: address.isDefault || false,
            tag: address.tag || ''
          },
          selectedTag: address.tag || '',
          region: [
            address.province || '请选择省市区', 
            address.city || '', 
            address.district || ''
          ]
        })
      } else {
        wx.showToast({
          title: res.message || '获取地址详情失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      console.error('获取地址详情失败:', err)
      this.setData({ loading: false })
      
      wx.showToast({
        title: '获取地址详情失败',
        icon: 'none'
      })
    })
  },

  onInput(e) {
    const { field } = e.currentTarget.dataset
    const { value } = e.detail
    
    this.setData({
      [`formData.${field}`]: value
    })
  },

  toggleDefault() {
    this.setData({
      'formData.isDefault': !this.data.formData.isDefault
    })
  },

  selectTag(e) {
    const tag = e.currentTarget.dataset.tag
    
    this.setData({
      selectedTag: tag === this.data.selectedTag ? '' : tag,
      'formData.tag': tag === this.data.selectedTag ? '' : tag
    })
  },

  onRegionChange(e) {
    const region = e.detail.value
    
    this.setData({
      region,
      'formData.province': region[0],
      'formData.city': region[1],
      'formData.district': region[2]
    })
  },

  showRegionPicker() {
    this.setData({
      showRegionPicker: true
    })
  },

  cancelRegionPicker() {
    this.setData({
      showRegionPicker: false
    })
  },

  chooseContact() {
    wx.chooseContact({
      success: (res) => {
        this.setData({
          'formData.name': res.displayName || res.nickName || '',
          'formData.phone': res.phoneNumber || ''
        })
      }
    })
  },

  saveAddress() {
    if (!this.validateForm()) {
      return
    }
    
    this.setData({ saving: true })
    
    const { formData, addressId } = this.data
    const isEdit = !!addressId
    
    const requestData = {
      ...formData,
      userId: app.getSafeUserId()
    }
    
    const apiPromise = isEdit
      ? request.put(`/address/${addressId}`, requestData, { mock: { success: true } })
      : request.post('/address', requestData, { mock: { id: Math.floor(Math.random() * 1000) + 3 } })
    
    apiPromise.then(res => {
      this.setData({ saving: false })
      
      if (res.code === 200) {
        wx.showToast({
          title: `${isEdit ? '修改' : '添加'}成功`,
          icon: 'success'
        })
        
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        wx.showToast({
          title: res.message || `${isEdit ? '修改' : '添加'}失败`,
          icon: 'none'
        })
      }
    }).catch(err => {
      console.error(`${isEdit ? '修改' : '添加'}地址失败:`, err)
      this.setData({ saving: false })
      
      wx.showToast({
        title: `${isEdit ? '修改' : '添加'}地址失败`,
        icon: 'none'
      })
    })
  },

  validateForm() {
    const { formData } = this.data
    
    if (!formData.name.trim()) {
      wx.showToast({
        title: '请输入联系人姓名',
        icon: 'none'
      })
      return false
    }
    
    if (!formData.phone.trim()) {
      wx.showToast({
        title: '请输入联系人电话',
        icon: 'none'
      })
      return false
    }
    
    if (!/^1\d{10}$/.test(formData.phone)) {
      wx.showToast({
        title: '手机号格式不正确',
        icon: 'none'
      })
      return false
    }
    
    if (!formData.province || formData.province === '请选择省市区') {
      wx.showToast({
        title: '请选择所在地区',
        icon: 'none'
      })
      return false
    }
    
    if (!formData.detailAddress.trim()) {
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      })
      return false
    }
    
    return true
  }
}) 